<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSSH</title>
    <link rel="stylesheet" href="/css/xterm.css" />
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/webuploader.css">
</head>
<body style="overflow-x: hidden;">
<div class="container-fluid">
    <div class="page-header" style="margin: 10px 0 0;">
            <div class="input-group">
                <span class="input-group-btn">
                    <button class="btn btn-warning" type="button" onclick="closeConnect()">
                        退出&nbsp;<span class="glyphicon glyphicon-off"></span>
                    </button>
                     <button title="返回上级" class="btn btn-default" type="button" onclick="back()">
                         返回上级&nbsp;<span class="glyphicon glyphicon-arrow-up"></span>
                     </button>
                        <button title="返回顶级" class="btn btn-default" type="button" onclick="listFiles('/')">
                         返回顶级&nbsp;<span class="glyphicon glyphicon-open"></span>
                     </button>
                     <button title="刷新" class="btn btn-default" type="button" onclick="listFiles(document.getElementById('search').value)">
                         刷新&nbsp;<span class="glyphicon glyphicon-refresh"></span>
                     </button>
                    <button title="搜索" class="btn btn-default" type="button" onclick="listFiles(document.getElementById('search').value)">
                     搜索&nbsp;<span class="glyphicon glyphicon-search"></span>
                    </button>
                 </span>
                <input id="search" type="text" class="form-control" placeholder="文件路径...">
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-3" id="upload">
            <div id="uploader-demo" style="text-align: center;margin-top: 10px;margin-bottom: 3px">
                <div id="filePicker" title="上传文件">上传文件（<3G）&nbsp;<span class="glyphicon glyphicon-cloud-upload"></span></div>
            </div>
            <table class="table table-hover" style="margin-bottom: 0">
                <tr>
                    <th>文件名</th>
                    <th width="125">操作</th>
                </tr>
            </table>
            <div id="tab-div" style="overflow-y: scroll">
                <table class="table table-hover" style='table-layout:fixed;'>
                    <tbody id="content">
                    </tbody>
                </table>
            </div>
        </div>
        <div id="terminal" class="col-md-9"></div>
    </div>
</div>
<script src="/js/jquery-3.4.1.min.js"></script>
<script src="/js/xterm.js" charset="utf-8"></script>
<script src="/js/webssh.js" charset="utf-8"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/js/webuploader.min.js"></script>
<script>
    $(function (){
        let obj = {
            host: '[[${loginInfo.host}]]',
            port: '[[${loginInfo.port}]]',
            username: '[[${loginInfo.username}]]',
            password: '[[${loginInfo.password}]]',
            check: '[[${loginInfo.check}]]'
        }
        //左侧文件目录栏
        $("#tab-div").css("height",$(window).height()-155);
        //文件上传插件
        var uploader = WebUploader.create({
            // 选完文件后，是否自动上传。
            auto: true,
            // swf文件路径
            swf: '/js/Uploader.swf',
            // 文件接收服务端。
            server: '/put',
            pick : {
                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                id : '#filePicker',
                //只能选择一个文件上传
                multiple: false
            },
            // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
            resize: false,
            // 单个文件总大小限制在3G
            fileSingleSizeLimit: 3000 * 1024 * 1024,
            //允许重复上传
            duplicate :true
        });
        uploader.on('beforeFileQueued', function (file) {
            uploader.options.formData.targetDir = $("#search").val();
            $("#filePicker").hide();
        });
        //验证文件文件大小
        uploader.on("error", function (type) {
            if (type == "F_EXCEED_SIZE") {
                alert("文件大小不能超过3G");
            }
        });

        // 文件上传过程中创建进度条实时显示。
        uploader.on( 'uploadProgress', function( file, percentage ) {
            $percent = $("#uploader-demo").find("#progressId");
            $percentChild = $percent.find(".progress-bar");
            if (!$percent.length) {
                let html = `<div id="progressId" class="progress" style="margin-left: 10px;margin-bottom: 20px; margin-top: 20px;">
                    <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100">
                    </div>
                </div>`;
                $("#uploader-demo").append(html);
            }
            $percentChild.css('width', percentage * 100 - 1 + '%')
            $percentChild.text(Math.floor(percentage * 100 -1) + '%');
        });
        // 文件上传成功，给item添加成功class, 用样式标记上传成功。
        uploader.on( 'uploadSuccess', function( file ) {
            let dom = $("#uploader-demo").find("#progressId").find(".progress-bar")
            dom.css('width', 100+'%')
            dom.text('100%')
            setTimeout(function(){
                alert("上传成功！");
                $("#uploader-demo").find("#progressId").remove();
                $("#filePicker").show();
                listFiles($("#search").val())
                }, 500);
        });
        // 文件上传失败，显示上传出错。
        uploader.on( 'uploadError', function( file ) {
            $("#uploader-demo").find("#progressId").remove();
            $("#filePicker").show();
            alert("上传失败！");
        });
        if([[${loginInfo.check}]]){
            localStorage.setItem("check",JSON.stringify(obj));
        }else {
            localStorage.removeItem("check");
        }
        $.ajax({
            url:"/ftpConnect",
            async:true,
            method: 'post',
            dataType:'json',
            data: obj,
            success:function(result){
                listFiles("/");
            },
            error:function (textStatus) {//请求失败后调用的函数
                alert("连接失败，请重新连接！");
                window.location.href='/close'
            }
        });
        openTerminal( {
            operate:'connect',
            host: obj.host,//IP
            port: obj.port,//端口号
            username: obj.username,//用户名
            password: obj.password//密码
        });
        function openTerminal(options){
            var client = new WSSHClient();
            var term = new Terminal({
                cols: 97,
                rows: Math.floor(window.screen.availHeight/25),
                cursorBlink: true, // 光标闪烁
                cursorStyle: "block", // 光标样式  null | 'block' | 'underline' | 'bar'
                scrollback: 800, //回滚
                tabStopWidth: 8, //制表宽度
                screenKeys: true
            });

            term.on('data', function (data) {
                //键盘输入时的回调函数
                client.sendClientData(data);
            });
            term.open(document.getElementById('terminal'));
            //在页面上显示连接中...
            term.write('Connecting...');
            //执行连接操作
            client.connect({
                onError: function (error) {
                    //连接失败回调
                    term.write('Error: ' + error + '\r\n');
                },
                onConnect: function () {
                    //连接成功回调
                    client.sendInitData(options);
                },
                onClose: function () {
                    //连接关闭回调
                    term.write("\rConnection closed");
                },
                onData: function (data) {
                    //收到数据时回调
                    term.write(data);
                }
            });
        }
    })
    //加载文件列表
    function listFiles(path){
        $("#content").empty();
        $("#search").val(path);
        $.ajax({
            url:"/listFiles",
            async:true,
            method: 'post',
            dataType:'json',
            data: {path: path},
            success:function(result){
                if(result.code === "0"){
                    let html = ''
                    $.each(result.data,function(index,value){
                        if(value.isDir){
                            html+=`<tr>
                                        <td style="overflow:hidden;white-space:nowrap;text-overflow:ellipsis;">
                                         <span class="glyphicon glyphicon-folder-open"></span>&nbsp;
                                          <a
                                          data-toggle="tooltip"
title="文件名：${value.fileName}
全路径：${value.fullFileName}
大小：${value.fileSize}
修改时间：${value.mtime}"
                                          style="cursor: pointer"
                                          onclick="listFiles('${value.fullFileName}')">
                                          ${value.fileName}</a>
                                        </td>
                                        <td></td>
                                   </tr>`
                        }else{
                            html+=`<tr>
                                        <td style="overflow:hidden;white-space:nowrap;text-overflow:ellipsis;">
                                          <span class="glyphicon glyphicon-file"></span>
                                          <span data-toggle="tooltip"
title="文件名：${value.fileName}
全路径：${value.fullFileName}
大小：${value.fileSize}
修改时间：${value.mtime}">
                                           ${value.fileName}
                                            </span>
                                         </td>
                                        <td align="center">
                                        <span class="glyphicon glyphicon-save" onclick="downloadFile('${value.fullFileName}')" style="cursor: pointer"></span>
                                        &nbsp;&nbsp;
                                        <span class="glyphicon glyphicon-trash" onclick="deleteFile('${value.fullFileName}')" style="cursor: pointer"></span>
                                        </td>
                                   </tr>`
                        }
                    });
                    $("[data-toggle='tooltip']").tooltip();
                    $("#content").append(html);
                }
            }});
    }
    //退出
    function back(){
        let val = $("#search").val();
        let backVal = val.substring(0, val.lastIndexOf("\/"));
        listFiles(backVal?backVal:"/");
    }
    //下载
    function downloadFile(fullFileName){
        window.location.href = "/down?fullFileName="+encodeURIComponent(fullFileName);
    }
    //删除
    function deleteFile(fullFileName){
        var r=confirm("确定删除改文件吗？");
        if (r===true)
        {
            $.ajax({
                url:"/deleteSingleFile",
                async:true,
                method: 'post',
                dataType:'json',
                data: {fullFileName: fullFileName},
                success:function(result){
                    if(result.code === '0'){
                        listFiles($("#search").val());
                    }else{
                        alert("删除失败！")
                    }
                }});
        }
        else{}
    }
    //退出
    function closeConnect(){
        var re=confirm("确定退出？");
        if (re===true)
        {
            window.location.href='/close'
        }
        else{}
    }
</script>
</body>
</html>
